<template>
    <VZPanel title="售后经销商4S店分布" simple iconText="mdi-chart-pie">
        <div style="margin:-16px">
            <v-card>
                <v-row>
                    <v-col cols="3">
                        <v-autocomplete
                                v-model="selectedReferred"
                                :items="referredItems"
                                item-text="text"
                                item-value="id"
                                label="搜索零件简称"
                                outlined
                                dense
                                clearable
                                :filter="customFilter"
                                :loading="loading"
                                multiple
                        ></v-autocomplete>
                    </v-col>
                    <v-col cols="3">
                        <v-autocomplete
                                v-model="selectedMaterial"
                                :items="materialItems"
                                item-text="text"
                                item-value="id"
                                label="搜索产品"
                                outlined
                                dense
                                clearable
                                :filter="customFilter"
                                :loading="loading"
                        ></v-autocomplete>
                    </v-col>
                    <v-col cols="2">
                        <v-menu
                                ref="startMenu"
                                v-model="startMenu"
                                :close-on-content-click="false"
                                max-width="290"
                                min-width="290"
                                offset-y
                        >
                            <template v-slot:activator="{ on, attrs }">
                                <v-text-field
                                        v-model="startYear"
                                        label="起始日期"
                                        readonly
                                        v-bind="attrs"
                                        v-on="on"
                                        outlined
                                        dense
                                ></v-text-field>
                            </template>
                            <v-date-picker
                                    v-model="startYear"
                                    type="month"
                                    @change="startMenu = false"
                                    :max="endYear"
                                    locale="zh-cn"
                            ></v-date-picker>
                        </v-menu>
                    </v-col>
                    <v-col cols="2">
                        <v-menu
                                ref="endMenu"
                                v-model="endMenu"
                                :close-on-content-click="false"
                                max-width="290"
                                min-width="290"
                                offset-y
                        >
                            <template v-slot:activator="{ on, attrs }">
                                <v-text-field
                                        v-model="endYear"
                                        label="结束日期"
                                        readonly
                                        v-bind="attrs"
                                        v-on="on"
                                        outlined
                                        dense
                                ></v-text-field>
                            </template>
                            <v-date-picker
                                    v-model="endYear"
                                    type="month"
                                    @change="endMenu = false"
                                    :min="startYear"
                                    locale="zh-cn"
                            ></v-date-picker>
                        </v-menu>
                    </v-col>
                    <v-spacer></v-spacer>
                    <v-col cols="auto" class="d-flex align-center">
                        <v-tooltip bottom>
                            <template v-slot:activator="{ on, attrs }">
                                <v-btn
                                    icon
                                    color="primary"
                                    @click="exportImage"
                                    :disabled="loading"
                                    v-bind="attrs"
                                    v-on="on"
                                    style="width: 36px; height: 36px"
                                >
                                    <v-icon size="24">mdi-image</v-icon>
                                </v-btn>
                            </template>
                            <span>导出图片</span>
                        </v-tooltip>
                    </v-col>
                </v-row>
                <div ref="target" style="width:100%;height:450px"></div>
                <v-data-table
                    :headers="headers"
                    :items="tableData"
                    :loading="loading"
                    :items-per-page="10"
                    class="elevation-1 mt-4"
                    :footer-props="{
                        'items-per-page-options': [10, 20, 50, -1],
                        'items-per-page-text': '每页行数'
                    }"
                    dense
                >
                    <template v-slot:top>
                        <v-toolbar flat>
                            <v-toolbar-title>4S店分布详情</v-toolbar-title>
                            <v-spacer></v-spacer>
                            <v-btn
                                icon
                                color="success"
                                @click="exportToExcel"
                                :disabled="loading"
                            >
                                <v-icon>mdi-file-excel</v-icon>
                            </v-btn>
                        </v-toolbar>
                    </template>
                    <template v-slot:item.percentage="{ item }">
                        {{ item.percentage }}%
                    </template>
                    <template v-slot:item.cumulative="{ item }">
                        {{ item.cumulative }}%
                    </template>
                </v-data-table>
            </v-card>
        </div>
    </VZPanel>
</template>

<script>
    export default {
        data() {
            return {
                nameList: [],
                numList: [],
                materialSql: "SELECT id,CONCAT(name,'   ',ASSEMBLY_CODE) name FROM tb_standard_assembly_product WHERE MARK_FOR_DELETE = 0",
                referredSql: "SELECT c.id,CONCAT(c.SIMPLE_CALL,'   ',c.CODE) name FROM tt_sale_record_qms a  " +
                    "LEFT JOIN tb_standard_assembly_product b ON a.MATERIAL_ID = b.ID " +
                    "LEFT JOIN tb_standard_assembly_product_referred c ON c.id = b.REFERRED_ID " +
                    "WHERE c.SIMPLE_CALL IS NOT NULL  " +
                    "GROUP BY c.ID ",
                materialItems: [],
                referredItems: [],
                searchMaterial: '',
                selectedMaterial: '',
                selectedReferred: [],
                yearOptions: [],
                startYear: '',
                endYear: '',
                startMenu: false,
                endMenu: false,
                loading: true,
                materialIds: [],
                headers: [
                    { text: '4S店名称', value: 'name', align: 'start' },
                    { text: '数量', value: 'value', align: 'end' },
                    { text: '占比(%)', value: 'percentage', align: 'end' },
                    { text: '累计占比(%)', value: 'cumulative', align: 'end' }
                ],
                tableData: [],
            }
        },
        computed: {
            years() {
                if (!this.startYear || !this.endYear) return [];
                const start = parseInt(this.startYear);
                const end = parseInt(this.endYear);
                return Array.from({length: end - start + 1}, (_, i) => String(start + i));
            }
        },
        methods: {
            run() {
                if (!this.chartTarget) {
                    this.chartTarget = this.$echarts.init(this.$refs.target);
                }
                this.chartTarget.clear();
                for (let i = 0; i < this.nameList.length; i++) {
                    if (this.nameList[i] === null || this.nameList[i] === undefined) {
                        this.nameList[i] = '未定义';
                    }
                }
                let total = this.numList.reduce((a, b) => a + b, 0);
                let percentList = this.numList.map(num => (num / total * 100).toFixed(1));
                let cumulative = [];
                let cumulativePercent = 0;
                this.numList.forEach(num => {
                    cumulativePercent += (num / total * 100);
                    cumulative.push(cumulativePercent.toFixed(1));
                });
                
                // 更新表格数据
                this.tableData = this.nameList.map((name, index) => ({
                    name: name,
                    value: this.numList[index],
                    percentage: percentList[index],
                    cumulative: cumulative[index]
                })).sort((a, b) => b.value - a.value);
                
                const that = this;
                let option = {
                    title: {
                        text: '售后分析缺陷模式分布',
                        left: 'center',
                        top: 20,
                        textStyle: {
                            fontSize: 16,
                            fontWeight: 'bold'
                        }
                    },
                    tooltip: {
                        trigger: 'item',
                        formatter: function(params) {
                            if (params.seriesName === '累计占比') {
                                return '累计占比: 100%';
                            }
                            return params.name + '<br/>' +
                                   '数量: ' + params.value + '<br/>' +
                                   '占比: ' + params.percent.toFixed(1) + '%';
                        }
                    },
                    legend: {
                        type: 'scroll',
                        orient: 'vertical',
                        right: '5%',
                        top: 'middle',
                        formatter: function(name) {
                            const index = that.nameList.indexOf(name);
                            if (index === -1) return name;
                            const value = that.numList[index];
                            const percent = percentList[index];
                            return name + '  ' + value + ' (' + percent + '%)';
                        }
                    },
                    series: [
                        {
                            name: '数量分布',
                            type: 'pie',
                            radius: ['40%', '70%'],
                            center: ['40%', '55%'],
                            avoidLabelOverlap: true,
                            itemStyle: {
                                borderRadius: 10,
                                borderColor: '#fff',
                                borderWidth: 2
                            },
                            label: {
                                show: true,
                                position: 'outside',
                                formatter: '{b}: {c} ({d}%)',
                                fontSize: 11
                            },
                            labelLine: {
                                show: true,
                                length: 10,
                                length2: 10
                            },
                            data: this.nameList.map((name, index) => ({
                                name: name,
                                value: this.numList[index]
                            })).sort((a, b) => b.value - a.value)
                        },
                        {
                            name: '累计占比',
                            type: 'pie',
                            radius: ['0%', '30%'],
                            center: ['40%', '55%'],
                            label: {
                                position: 'center',
                                formatter: '累计\n100%',
                                fontSize: 20,
                                fontWeight: 'bold'
                            },
                            data: [{
                                value: 100,
                                name: '累计占比',
                                itemStyle: {
                                    color: '#67C23A'
                                }
                            }]
                        }
                    ]
                };
                this.chartTarget.setOption(option);
            },
            search_data() {
                if (this.materialIds.length === 0) {
                    return;
                }
                let _this = this;
                this.loading = true;
                let params = {
                    "SQL": `SELECT IFNULL(a.REPAIR_STATION_NAME, '未定义') name, COUNT(1) num
                    FROM tt_sale_record_qms a
                    WHERE a.MATERIAL_ID in (${this.materialIds.join(',')})
                    AND (DATE_FORMAT(a.MADE_TIME, '%Y-%m') >= '${this.startYear}'
                    AND DATE_FORMAT(a.MADE_TIME, '%Y-%m') <= '${this.endYear}')
                    GROUP BY a.REPAIR_STATION_NAME
                    ORDER BY num DESC`
                };
                app.utils.ajaxRequest({
                    hideMsg: true,
                    hideMask: true,
                    url: app.path().dispose + "?functionCode=QMS_CUSTOM_QUERY_SQL",
                    params: {
                        functionParam: JSON.stringify(params)
                    },
                    callBack(res) {
                        if (res.success) {
                            _this.nameList = res.rows.map(item => item.name || '未定义');
                            _this.numList = res.rows.map(item => item.num);
                            _this.run();
                        }
                        _this.loading = false;
                    },
                });
            },
            loadReferredData() {
                let _this = this;
                _this.referredItems = [];
                let params = {"SQL": this.referredSql};
                app.utils.ajaxRequest({
                    hideMsg: true,
                    hideMask: true,
                    url: app.path().dispose + "?functionCode=QMS_CUSTOM_QUERY_SQL",
                    params: {
                        functionParam: JSON.stringify(params)
                    },
                    callBack(res) {
                        if (res.success && res.rows.length > 0) {
                            let dataList = res.rows;
                            let referredList = [];
                            dataList.forEach((item) => {
                                let map = {};
                                map.text = item.name;
                                map.id = item.id;
                                referredList.push(map);
                            })
                            _this.referredItems = referredList;
                            if (_this.referredItems.length > 0) {
                                _this.selectedReferred = [_this.referredItems[0].id];
                                _this.loadMaterialIdsByReferred().then(() => {
                                    if (_this.materialIds.length > 0) {
                                        _this.search_data();
                                    }
                                });
                            }
                        }
                    },
                })
            },
            loadMaterialData() {
                let _this = this;
                _this.materialItems = [];
                let params = {"SQL": this.materialSql};
                app.utils.ajaxRequest({
                    hideMsg: true,
                    hideMask: true,
                    url: app.path().dispose + "?functionCode=QMS_CUSTOM_QUERY_SQL",
                    params: {
                        functionParam: JSON.stringify(params)
                    },
                    callBack(res) {
                        if (res.success && res.rows.length > 0) {
                            let dataList = res.rows;
                            let materialList = [];
                            dataList.forEach((item) => {
                                let map = {};
                                map.text = item.name;
                                map.id = item.id;
                                materialList.push(map);
                            })
                            _this.materialItems = materialList;
                        }
                        _this.loading = false;
                    },
                })
            },
            loadMaterialIdsByReferred() {
                if (!this.selectedReferred.length) {
                    this.materialIds = this.selectedMaterial ? [this.selectedMaterial] : [];
                    return Promise.resolve();
                }
                let _this = this;
                let params = {
                    "SQL": `SELECT DISTINCT a.id
                    FROM tb_standard_assembly_product a
                    WHERE a.MARK_FOR_DELETE = 0
                    AND a.REFERRED_ID IN (${this.selectedReferred.join(',')})`
                };
                return new Promise((resolve) => {
                    app.utils.ajaxRequest({
                        hideMsg: true,
                        hideMask: true,
                        url: app.path().dispose + "?functionCode=QMS_CUSTOM_QUERY_SQL",
                        params: {
                            functionParam: JSON.stringify(params)
                        },
                        callBack(res) {
                            if (res.success && res.rows.length > 0) {
                                _this.materialIds = res.rows.map(item => item.id);
                            } else {
                                _this.materialIds = [];
                            }
                            resolve();
                        },
                    });
                });
            },
            initYearOptions() {
                const currentDate = new Date();
                const currentYear = currentDate.getFullYear();
                const currentMonth = String(currentDate.getMonth() + 1).padStart(2, '0');
                this.endYear = `${currentYear}-${currentMonth}`;
                
                // 设置起始日期为一年前
                const startDate = new Date(currentDate);
                startDate.setFullYear(currentYear - 1);
                this.startYear = `${startDate.getFullYear()}-${String(startDate.getMonth() + 1).padStart(2, '0')}`;
            },
            reset() {
                this.searchMaterial = '';
                this.selectedMaterial = '';
                this.selectedReferred = [];
                this.startYear = '';
                this.endYear = '';
                this.search_data();
            },
            customFilter(item, queryText, itemText) {
                const textOne = itemText.toLowerCase();
                const searchText = queryText.toLowerCase();
                return textOne.indexOf(searchText) > -1;
            },
            exportImage() {
                if (!this.chartTarget) {
                    app.$message.warning('图表未初始化');
                    return;
                }
                
                const imageUrl = this.chartTarget.getDataURL({
                    type: 'png',
                    pixelRatio: 2,
                    backgroundColor: '#fff'
                });
                
                const link = document.createElement('a');
                link.download = `售后经销商4S店分布_${this.startYear}_${this.endYear}.png`;
                link.href = imageUrl;
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
            },
            exportToExcel() {
                if (this.tableData.length === 0) {
                    app.$message.warning('暂无数据可导出');
                    return;
                }

                // 创建CSV内容
                let csvContent = '\uFEFF'; // 添加BOM以支持中文
                
                // 添加表头
                csvContent += '4S店名称,数量,占比(%),累计占比(%)\n';
                
                // 添加数据行
                this.tableData.forEach(item => {
                    csvContent += `${item.name},${item.value},${item.percentage},${item.cumulative}\n`;
                });

                // 创建Blob对象
                const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
                
                // 创建下载链接
                const link = document.createElement('a');
                link.href = URL.createObjectURL(blob);
                link.download = `售后经销商4S店分布_${this.startYear}_${this.endYear}.csv`;
                
                // 触发下载
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
                URL.revokeObjectURL(link.href);
            },
        },
        watch: {
            selectedMaterial() {
                if (this.selectedMaterial) {
                    this.selectedReferred = [];
                    this.materialIds = [this.selectedMaterial];
                    this.search_data();
                }
            },
            async selectedReferred() {
                if (this.selectedReferred.length) {
                    this.selectedMaterial = '';
                    await this.loadMaterialIdsByReferred();
                    if (this.materialIds.length > 0) {
                        this.search_data();
                    }
                } else {
                    if (!this.selectedMaterial) {
                        this.materialIds = [];
                    }
                }
            },
            startYear() {
                if (this.materialIds.length > 0) {
                    this.search_data();
                }
            },
            endYear() {
                if (this.materialIds.length > 0) {
                    this.search_data();
                }
            }
        },
        created() {
            this.initYearOptions();
            this.loadMaterialData();
            this.loadReferredData();
            setTimeout(() => {
                this.search_data();
            }, 1000);
        },
        mounted() {
            window.onresize = () => {
                this.chartTarget.resize();
            }
        },
    }
</script>
